/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.perlak.camel.search;

import com.google.protobuf.ByteString;
import com.perlak.camel.BaseMultiProcessor;
import com.perlak.filesearch.FileScanner;
import com.perlak.filesearch.FileSearchRequest;
import com.perlak.filesearch.FileSearchResult;
import com.perlak.filesearch.SingleFileResult;
import com.perlak.messages.FileSearch.fileSearchJob;
import com.perlak.messages.FileSearch.fileSearchRequest;
import com.perlak.messages.FileSearch.fileSearchResult;
import com.perlak.messages.FileSearch.singleFileResult;
import java.util.ArrayList;
import java.util.List;
import org.apache.camel.Exchange;
import org.apache.commons.httpclient.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author mateusz
 */
public class SearchProcessor extends BaseMultiProcessor {

  public static final int SEARCH_REQUEST = 1;

  public SearchProcessor(final int type) {
    super(type);
  }

  @Override
  protected void processNoError(final Exchange exchange) throws Exception {
    switch (processType) {
      case SEARCH_REQUEST:
        searchRequestProcess(exchange);
        break;
      default:

    }
  }

  private void searchRequestProcess(final Exchange exchange) throws Exception {
    fileSearchJob searchJob = fileSearchJob.parseFrom(exchange.getIn().getBody(ByteString.class));
    List<FileSearchRequest> searchRequestList = new ArrayList<FileSearchRequest>();
    for(fileSearchRequest fsReqProto : searchJob.getRequestList())
    {
      FileSearchRequest fsReq = SearchMessageTranslator.translate(fsReqProto);
      getLog().debug("search request translated: {}", fsReq.toString());
      searchRequestList.add(fsReq);
    }
    
    FileScanner scanner = new FileScanner(searchRequestList);
    scanner.search();
    List<FileSearchResult> fsResList = scanner.getResults();
    fileSearchResult.Builder resBuild = fileSearchResult.newBuilder();
    
    for(FileSearchResult fsRes : fsResList) {
      for (SingleFileResult fsSingleRes: fsRes.getFiles() ){
        singleFileResult singleFile = SearchMessageTranslator.translate(fsSingleRes);
        resBuild.addFileDetail(singleFile);
      }
    }

    exchange.getOut().setBody(resBuild.build().toByteString());
  }

  /**
   * Gets logger for this class.
   * @return logger
   */
  @Override
  public Logger getLog() {
    return LoggerFactory.getLogger(SearchProcessor.class);
  }
}
